package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.RecordCourse;
import com.xmy.cultivate.entity.RepairCourse;
import com.xmy.cultivate.entity.Student;
import com.xmy.cultivate.entity.StudentGrade;
import com.xmy.cultivate.mapper.CourseSchedulingDetailMapper;
import com.xmy.cultivate.mapper.OrderDetailMapper;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.mapper.StudentMapper;
import com.xmy.cultivate.service.IWecharPushService;
import com.xmy.cultivate.service.IWecharsBindService;
import com.xmy.cultivate.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class WecharPushServiceImpl implements IWecharPushService {


    @Autowired
    CourseSchedulingDetailMapper courseSchedulingDetailMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IWecharsBindService iWecharsBindService;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    /**
     * 推送第二天要上课的学生信息
     */
    @Override
    public void attendClassRemind() {
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        LocalDate localDate = LocalDate.now().plusDays(1);
        repairCourseQueryWrapper.eq("school_date", localDate);
        repairCourseQueryWrapper.eq("status", 0);

        List<RepairCourse> repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepair(repairCourseQueryWrapper);

        //System.out.println("repairCourseListCount:"+repairCourseList.size());

        for (RepairCourse repairCourse : repairCourseList) {
            try {
                if (!repairCourse.getLessonType().equals(1)) {
                    //智能课、刷题班
                    this.otherCourse(repairCourse);
                }else {
                    //精品课
                    this.boutiqueCourse(repairCourse);
                }


            } catch (Exception e) {

            }
        }
    }

    /**
     * 精品课推送
     * @param repairCourse
     */
    private void boutiqueCourse(RepairCourse repairCourse){
        //1按班级正常排课、调课，2按学员调课、补课，消课
        if (repairCourse.getSchedulingType().equals(1)) {
            //课程类别：1精品课，2智能课，3补课，4调课，5消课
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("grade_id", repairCourse.getGradeId());
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted=0 and out_scheduling_detail_id=" + repairCourse.getId() + "");
            studentGradeQueryWrapper.groupBy("student_id");
            List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
            //System.out.println("studentGradeListCount:"+studentGradeList.size());
            for (StudentGrade studentGrade : studentGradeList) {
                Integer yearAndQuarter = Integer.parseInt(studentGrade.getYearPart() + "" + studentGrade.getQuarterNum());
                Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(studentGrade.getSchoolId(), studentGrade.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, studentGrade.getLessonType(),studentGrade.getYearClassId());
                if (residueCourseCount > 0) {
                    Student student = studentMapper.selectById(studentGrade.getStudentId());
                    if (student != null) {
                        if (repairCourse.getCourseType().equals(1)) {
                            //班级里的上课学生
                            StringBuilder first = new StringBuilder();
                            first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");

                            //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                            String keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());

                            StringBuilder keyword2 = new StringBuilder();
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                            // 使用formatter格式化LocalDateTime
                            String sortDateTime = repairCourse.getStartDateTime().format(formatter);
                            //String sortDateTime = repairCourse.getStartDateTime().toString();

                            //keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                            keyword2.append(sortDateTime);


                            StringBuilder remark = new StringBuilder();
                            remark.append("如有疑问，请与老师联系");
                            List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                            iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                        } else {
                            //班级里的调课学生
                            StringBuilder first = new StringBuilder();
                            first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");
                            String keyword1 = "";
                            if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                                keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                            } else {
                                //String teacherName =  studentGradeMapper.getTeacherNameForGradeId(studentGrade.getGradeId());
                                keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();

                            }

                            StringBuilder keyword2 = new StringBuilder();
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                            // 使用formatter格式化LocalDateTime
                            String sortDateTime = repairCourse.getStartDateTime().format(formatter);
                            //String sortDateTime = repairCourse.getStartDateTime().toString();

                            keyword2.append(sortDateTime);
                            //keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                            StringBuilder remark = new StringBuilder();
                            remark.append("如有疑问，请与老师联系");
                            List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                            iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                        }
                    }
                }


            }
        } else if (repairCourse.getSchedulingType().equals(2)) {
            Integer yearAndQuarter = Integer.parseInt(repairCourse.getYearPart() + "" + repairCourse.getQuarter());
            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourse.getSchoolId(), repairCourse.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, repairCourse.getLessonType(),repairCourse.getYearClassId());
            if (residueCourseCount > 0) {
                Student student = studentMapper.selectById(repairCourse.getStudentId());
                if (student != null) {
                    StringBuilder first = new StringBuilder();
                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");

                    String keyword1 = "";
                    if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                        keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                    } else {
                        keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();
                        try {
                            RecordCourse recordCourse = studentGradeMapper.getLastReadingGrade(repairCourse.getYearPart(), repairCourse.getQuarter(), repairCourse.getSchoolId(), repairCourse.getSubjectsId(), repairCourse.getStudentId());
                            String gradeName = recordCourse.getGradeName();
                            gradeName = this.replaceGradeName(gradeName, recordCourse.getTeacherName(),student.getName(), repairCourse.getSubjectsName());
                            keyword1 = gradeName;
                        } catch (Exception e) {
                        }
                    }

                    StringBuilder keyword2 = new StringBuilder();
                    //keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");

                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                    // 使用formatter格式化LocalDateTime
                    String sortDateTime = repairCourse.getStartDateTime().format(formatter);
                    if (repairCourse.getCourseType().equals(3) || repairCourse.getCourseType().equals(6)){
                        sortDateTime = repairCourse.getSchoolDate()+" "+ repairCourse.getTimeStart()+"-"+repairCourse.getTimeEnd();
                    }

                    keyword2.append(sortDateTime);

                    StringBuilder remark = new StringBuilder();
                    remark.append("如有疑问，请与老师联系");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(repairCourse.getStudentId());
                    iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                }
            }
        }
    }

    /**
     * 智能课，或者刷题班
     * @param repairCourse
     */
    private void otherCourse(RepairCourse repairCourse){

        Integer lessonType = 1;//这里计算精品课的剩余课时

        if (repairCourse.getSchedulingType().equals(1)) {
            //课程类别：1精品课，2智能课，3补课，4调课，5消课
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("grade_id", repairCourse.getGradeId());
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted=0 and out_scheduling_detail_id=" + repairCourse.getId() + "");
            studentGradeQueryWrapper.groupBy("student_id");
            List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
            //System.out.println("studentGradeListCount:"+studentGradeList.size());

            String lessonName = CommonUtil.getLessonTypeName(repairCourse.getLessonType());

            for (StudentGrade studentGrade : studentGradeList) {



                Integer yearAndQuarter = Integer.parseInt(studentGrade.getYearPart() + "" + studentGrade.getQuarterNum());
                Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(studentGrade.getSchoolId(), studentGrade.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, lessonType,studentGrade.getYearClassId());
                if (residueCourseCount > 0) {
                    Student student = studentMapper.selectById(studentGrade.getStudentId());
                    if (student != null) {
                        StringBuilder first = new StringBuilder();
                        first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“"+lessonName+"”上课提醒");

                        //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                        //【刘小铭】英语智能课/刷题班
                        String keyword1 = "【"+student.getName()+"】"+repairCourse.getSubjectsName()+lessonName;
                        StringBuilder keyword2 = new StringBuilder();
                        //keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                        keyword2.append(repairCourse.getSchoolDate().toString().replace("T", " ") + "上课");
                        StringBuilder remark = new StringBuilder();
                        remark.append("如有疑问，请与老师联系");
                        List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                        iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                    }
                }
            }
        } else if (repairCourse.getSchedulingType().equals(2)) {
            Integer yearAndQuarter = Integer.parseInt(repairCourse.getYearPart() + "" + repairCourse.getQuarter());
            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjectsNoYearClassId(repairCourse.getSchoolId(), repairCourse.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, lessonType);
            if (residueCourseCount > 0) {
                Student student = studentMapper.selectById(repairCourse.getStudentId());
                String lessonName = CommonUtil.getLessonTypeName(repairCourse.getLessonType());
                if (student != null) {
                    StringBuilder first = new StringBuilder();
                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“"+lessonName+"”上课提醒");

                    //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                    //【刘小铭】英语智能课/刷题班
                    String keyword1 = "【"+student.getName()+"】"+repairCourse.getSubjectsName()+lessonName;
                    StringBuilder keyword2 = new StringBuilder();
                    //keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                    keyword2.append(repairCourse.getSchoolDate().toString().replace("T", " ") + "上课");
                    StringBuilder remark = new StringBuilder();
                    remark.append("如有疑问，请与老师联系");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(repairCourse.getStudentId());
                    iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                }
            }
        }
    }

    /**
     * 取消上课
     */
    @Override
    public void cancClassRemind(){
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        LocalDate localDate = LocalDate.now().plusDays(1);
        repairCourseQueryWrapper.eq("school_date", localDate);
        repairCourseQueryWrapper.eq("status", 2);

        List<RepairCourse> repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepair(repairCourseQueryWrapper);

        //System.out.println("repairCourseListCount:"+repairCourseList.size());

        for (RepairCourse repairCourse : repairCourseList) {
            try {
                if (!repairCourse.getLessonType().equals(1)) {
                    continue;
                }

                //1按班级正常排课、调课，2按学员调课、补课，消课
                if (repairCourse.getSchedulingType().equals(1)) {
                    //课程类别：1精品课，2智能课，3补课，4调课，5消课
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("grade_id", repairCourse.getGradeId());
                    studentGradeQueryWrapper.eq("reading_status", 1);
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted=0 and out_scheduling_detail_id=" + repairCourse.getId() + "");
                    studentGradeQueryWrapper.groupBy("student_id");
                    List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
                    //System.out.println("studentGradeListCount:"+studentGradeList.size());
                    for (StudentGrade studentGrade : studentGradeList) {
                        Integer yearAndQuarter = Integer.parseInt(studentGrade.getYearPart() + "" + studentGrade.getQuarterNum());
                        Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(studentGrade.getSchoolId(), studentGrade.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, studentGrade.getLessonType(),studentGrade.getYearClassId());
                        if (residueCourseCount > 0) {
                            Student student = studentMapper.selectById(studentGrade.getStudentId());
                            if (student != null) {
                                if (repairCourse.getCourseType().equals(1)) {
                                    //班级里的上课学生
                                    StringBuilder first = new StringBuilder();
                                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”");

                                    //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                                    String keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());

                                    StringBuilder keyword2 = new StringBuilder();
                                    keyword2.append(repairCourse.getSchoolDate() + "会进行调课");
                                    StringBuilder remark = new StringBuilder();
                                    remark.append("如有疑问，请与老师联系");
                                    List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                                    iWecharsBindService.wxCalOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                                } else {
                                    //班级里的调课学生
                                    StringBuilder first = new StringBuilder();
                                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”");
                                    String keyword1 = "";
                                    if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                                        keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                                    } else {
                                        //String teacherName =  studentGradeMapper.getTeacherNameForGradeId(studentGrade.getGradeId());
                                        keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();

                                    }

                                    StringBuilder keyword2 = new StringBuilder();
                                    keyword2.append(repairCourse.getSchoolDate()+ "会进行调课");
                                    StringBuilder remark = new StringBuilder();
                                    remark.append("如有疑问，请与老师联系");
                                    List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                                    iWecharsBindService.wxCalOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                                }
                            }
                        }


                    }
                } else if (repairCourse.getSchedulingType().equals(2)) {
                    Integer yearAndQuarter = Integer.parseInt(repairCourse.getYearPart() + "" + repairCourse.getQuarter());
                    Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourse.getSchoolId(), repairCourse.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, repairCourse.getLessonType(),repairCourse.getYearClassId());
                    if (residueCourseCount > 0) {
                        Student student = studentMapper.selectById(repairCourse.getStudentId());
                        if (student != null) {
                            StringBuilder first = new StringBuilder();
                            first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”");

                            String keyword1 = "";
                            if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                                keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                            } else {
                                keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();
                                try {
                                    RecordCourse recordCourse = studentGradeMapper.getLastReadingGrade(repairCourse.getYearPart(), repairCourse.getQuarter(), repairCourse.getSchoolId(), repairCourse.getSubjectsId(), repairCourse.getStudentId());
                                    String gradeName = recordCourse.getGradeName();
                                    gradeName = this.replaceGradeName(gradeName, recordCourse.getTeacherName(),student.getName(), repairCourse.getSubjectsName());
                                    keyword1 = gradeName;
                                } catch (Exception e) {
                                }
                            }

                            StringBuilder keyword2 = new StringBuilder();
                            keyword2.append(repairCourse.getSchoolDate()+ "会进行调课");
                            StringBuilder remark = new StringBuilder();
                            remark.append("如有疑问，请与老师联系");
                            List<String> opendIdList = iWecharsBindService.getSendOpenid(repairCourse.getStudentId());
                            iWecharsBindService.wxCalOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                        }
                    }
                }
            } catch (Exception e) {

            }
        }
    }


    private String replaceGradeName(String gradeName,String teacherName, String studentName, String subjectsName) {
        String keyword1 = gradeName;
        if (keyword1.contains("【" + teacherName + "】")) {
            keyword1 = keyword1.replace("【" + teacherName + "】", "【" + studentName + "】" + subjectsName);
        } else if (keyword1.contains("【" + subjectsName + "】")) {
            keyword1 = keyword1.replace("【" + subjectsName + "】", "【" + studentName + "】" + subjectsName);
        } else if (keyword1.contains(teacherName)) {
            keyword1 = keyword1.replace(teacherName, studentName);
            keyword1 += subjectsName;
        } else {
            keyword1 = "【" + studentName + "】" + subjectsName;
        }
        return keyword1;
    }

    String replaceGradeName2(String gradeName,String studentName, String subjectsName){
        //String text = "这是一个示例文本【第一组数据】和其他数据【第二组数据】结束。";
        Pattern pattern = Pattern.compile("【(.*?)】");
        Matcher matcher = pattern.matcher(gradeName);
        String keyword1 = "";
        while (matcher.find()) {
            //System.out.println(matcher.group(1));
            keyword1 = matcher.group(1);
        }
        if (StringUtils.isNotBlank(keyword1)){
            gradeName = gradeName.replace(keyword1,studentName);
        }
        return gradeName;
    }
}
